<template>
    <div class="isDialog">
        <div>
            <div>
                <el-form :model="stockQuery" ref="form" label-width="90px" :inline="true">
                    <el-form-item label="仓库：">
                        <el-select v-model="stockQuery.deoptId" placeholder="请选择仓库" clearable filterable multiple>
                            <el-option v-for="item in depots" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品信息：">
                        <el-input v-model="stockQuery.materialInformation" placeholder="条码/名称/规格/型号/颜色" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="findMaterialStock" style="margin-left: 20px;">
                            查询
                        </el-button>
                        <el-button @click="exportBtn">
                            <el-icon class="el-icon--left">
                                <Download />
                            </el-icon>
                            导出
                        </el-button>
                        <el-button type="primary" size="default" link @click="visibleClick">
                            {{ visible ? '收起' : '展开' }}
                            <el-icon :style="{ transform: visible ? 'rotate(180deg)' : 'rotate(0deg)' }">
                                <ArrowUp />
                            </el-icon>
                        </el-button>

                        <el-form-item style="margin-left: 120px;">
                            <el-space>
                                <span>
                                    总库存：{{ total.inventory }}
                                </span>
                                <span>
                                    总库存金额：{{ total.money }}
                                </span>
                                <span>
                                    总重量：{{ total.weight }}
                                </span>
                            </el-space>
                        </el-form-item>

                    </el-form-item>

                    <div v-if="visible">
                        <el-form-item label="类别：">
                            <el-tree-select v-model="stockQuery.categoryId" :data="materialCategoryTree" check-strictly
                                :props="{ children: 'children', label: 'orgAbr', value: 'id' }"
                                :default-expand-all="true" :render-after-expand="false" placeholder="请选择商品类别"
                                clearable />
                        </el-form-item>
                        <el-form-item label="仓位货架：">
                            <el-input v-model="stockQuery.position" placeholder="请输入仓位货架查询" clearable />
                        </el-form-item>
                        <el-form-item label="零库存：">
                            <el-select v-model="stockQuery.isInventory" filterable>
                                <el-option v-for="item in StatusOptions" :key="item.label" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div>
                <el-table ref="tableRef" :data="page.records" border show-summary :summary-method="getSummaries" stripe
                    max-height="489px">
                    <el-table-column label="#" type="index" width="70" align="center" />
                    <el-table-column label="库存流水" width="90" align="center">
                        <template #default="scope">
                            <el-button type="primary" link :row="scope.row"
                                v-perm:report:material_stock:findMaterialBill="findMaterialStockBill">流水</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column v-for="col in tableHeader" :prop="col.prop" :key="col.id" :label="col.label"
                        :sortable="col.sortable" />
                </el-table>
            </div>
            <Pagination :current="page.current" :page-size="page.size" :total="page.total" @change="findMaterialStock"
                @update:pageSize="sizeChange" @update:current="currentChange" />
        </div>


        <el-dialog :title="dialogTitle" v-model="dialogVisible" :destroy-on-close="true" draggable width="70%"
            :before-close="close">
            <router-view @close="close" @jump="jumpBillDetail" :data="data"></router-view>
        </el-dialog>

        <el-dialog title="详情" v-model="detailDialogVisible" :destroy-on-close="true" draggable width="85%">
            <template v-if="depotHead.type === '入库'">
                <Stockroom :depot-head="depotHead" @close="closeTwo" />
            </template>
            <template v-else-if="depotHead.type === '出库'">
                <Allocate :depot-head="depotHead" @close="closeTwo" />
            </template>
        </el-dialog>
    </div>


</template>

<script lang='ts' setup>
import { ref, computed, onMounted } from 'vue'
import request from '@/api/request'
import router from '@/router'
import { TableColumnCtx } from 'element-plus'
import { exportTable } from '@/utils/xlsx'
import Pagination from '@/components/pagination/Index.vue'
// 出库页面
import Allocate from '@/components/material_bill_detail/Allocate.vue'
let visible = ref(false)
const tableRef = ref(null)
let dialogTitle = ref('');
let dialogVisible = ref(false)
let detailDialogVisible = ref(false)
let data = ref({})

let depots = ref([])

// 入库/退货
import Stockroom from '@/components/material_bill_detail/Stockroom.vue'


class Stater {
    deoptId: Array<Number>; // 仓库id
    materialInformation: String; // 商品信息
    categoryId: Number; // 类别id
    position: String; // 仓位货架
    isInventory: Number; // 零库存
};
// 商品库存查询条件
const stockQuery = ref(new Stater);
// 仓库
const deopt = ref([])
// 商品类别
const materialCategoryTree = ref([])

const page = ref({
    current: 1,
    size: 5,
    pages: 1,
    total: 1,
    records: null
});


let depotHead = ref({
    type: null // 1：入库、2：出库
})
/**
 * 跳转商品库存流水
 */
const jumpBillDetail = (item) => {
    depotHead = ref({ ...item })
    detailDialogVisible.value = true
};

// 入库
// const getStockRoom = (depotHeadTwo) => {
//     depotHead = ref({ ...depotHeadTwo })
//     detailDialogVisible.value = true
// }

const visibleClick = () => {
    visible.value = !visible.value
};

const StatusOptions = [
    { label: "隐藏", value: 1 },
    { label: "显示", value: 2 },
];


var total = ref({
    inventory: null,
    money: null,
    weight: null
})
const findMaterialStock = () => {
    console.log(stockQuery.value);

    request.get('report/findMaterialStock', {
        params: {
            ...stockQuery.value, current: page.value.current, size: page.value.size
        }
    }).then(resp => {
        page.value = resp.data
    })
};

const sizeChange = (pageSize: number) => {
    page.value.size = pageSize;
    findMaterialStock
}

const currentChange = (pageCurrent: number) => {
    page.value.current = pageCurrent;
    findMaterialStock
}
/**
 * @param p 权限对象
 * @param row 当前行数据
 */
const findMaterialStockBill = (p: any, row: any) => {
    // FindBill.vue
    dialogTitle.value = p.cname
    data.value = row
    router.push(p.path)
    dialogVisible.value = true
}

interface Product {
    id: string
    name: string
    amount1: string
    amount2: string
    amount3: number
};

interface SummaryMethodProps<T = Product> {
    columns: TableColumnCtx<T>[]
    data: T[]
};

const getSummaries = (param: SummaryMethodProps) => {
    const { columns, data = [] } = param
    const sums: string[] = []
    columns.forEach((column, index) => {

        if (index === 0) {
            sums[index] = '合计'
            return;
        }
        if (Array.isArray(data)) {
            const values = data.map((item) => Number(item[column.property]))
            if (column.property === 'currentStock' || column.property === 'currentStockPrice' || column.property === 'currentWeight') {
                sums[index] = ` ${values.reduce((prev, curr) => {
                    const value = Number(curr)
                    if (!Number.isNaN(value)) {
                        return prev + curr
                    } else {
                        return prev
                    }
                }, 0)}`
                if (column.property === 'currentStock') {
                    total.value.inventory = sums[index]
                } else if (column.property === 'currentStockPrice') {
                    total.value.money = sums[index]
                } else if (column.property === 'currentWeight') {
                    total.value.weight = sums[index]
                }
            } else {
                sums[index] = ''
            }
        }
    })
    return sums
};

// 处理未选择商品类别显示
computed({
    get() {
        return stockQuery.value.categoryId === 0 ? null : stockQuery.value.categoryId;
    },
    set(value) {
        stockQuery.value.categoryId = value;
    }
});

const tableHeader = ref([
    {
        id: 1,
        label: '条码',
        prop: 'barCode'
    },
    {
        id: 2,
        label: '名称',
        prop: 'materialName'
    },
    {
        id: 3,
        label: '规格',
        prop: 'specs'
    },
    {
        id: 4,
        label: '型号',
        prop: 'model'
    },
    {
        id: 5,
        label: '颜色',
        prop: 'color'
    },
    {
        id: 6,
        label: '类别',
        prop: 'categoryName'
    },
    {
        id: 7,
        label: '仓位货架',
        prop: 'position'
    },
    {
        id: 8,
        label: '单位',
        prop: 'unitName'
    },
    {
        id: 9,
        label: '单价',
        prop: 'purchasePrice',
        sortable: true
    },
    {
        id: 10,
        label: '库存',
        prop: 'currentStock',
        sortable: true
    },
    {
        id: 11,
        label: '最低库存数量',
        prop: 'initialInventory',
        sortable: true
    },
    {
        id: 12,
        label: '建议入库数量',
        prop: 'inventoryNumber',
        sortable: true
    },
    {
        id: 13,
        label: '库存金额',
        prop: 'currentStockPrice',
        sortable: true
    },
    {
        id: 14,
        label: '重量',
        prop: 'currentWeight',
        sortable: true
    }
]);

const exportBtn = () => {
    exportTable(tableRef, '商品库存报表')
}

const close = () => {
    dialogVisible.value = !dialogVisible.value
}

const closeTwo = () => {
    detailDialogVisible.value = false
}

const findDepotByTenantId = async () => {
    await request.get('depot/findDepotByTenantId').then(resp => {
        console.log(resp);
        depots.value = resp.data
    })
}

onMounted(() => {
    stockQuery.value.isInventory = 1

    findDepotByTenantId()
    findMaterialStock()
})
</script>

<style scoped>
.pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;
}

.el-select {
    width: 200px;
}

.el-input {
    width: 200px;
}
</style>
